/**
 *   yzz
 *  在线检核2016 12 22
 */
// 自定义了一个Map对象，类似Java里的Map 对象


var hvectorSource;
var hvector_layer;
var aduitask_layer;
var aduitask_source;
var showSource = new ol.source.Vector();
var showfill = new ol.style.Fill({
    color: 'rgba(255, 0, 0, 0)'
});

$("document").ready(function () {

    queryTaskList();
    $("#queryBtn").on("click", function () {
        showSource.clear();
        CQuery();
    });
});

/**
 * 地图容器
 */
var hmap = new ol.Map(
    {
        layers: [
            new ol.layer.Group(
                {
                    'title': '基础底图',
                    layers: [
                        new ol.layer.Tile(
                            {
                                title: ' 必应影像',
                                type: 'base',
                                source: new ol.source.BingMaps({
                                    imagerySet: 'Aerial',
                                    key: 'AkGbxXx6tDWf1swIhPJyoAVp06H0s0gDTYslNWWHZ6RoPqMpB9ld5FY1WutX8UoF'
                                })
                            })
                    ]
                })
        ],
        target: 'hmap',
        view: new ol.View({
            center: [11842307, 4098936],
            zoom: 3
        })
    });

/**
 * 任务图层
 */
aduitask_source = new ol.source.Vector;
aduitask_layer = new ol.layer.Vector({
    name: '任务图层',
    source: aduitask_source, // 加载数据源
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255,0)'
        }),
        stroke: new ol.style.Stroke({
            color: '#72ff52',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({
                color: '#ffcc33'
            })
        })
    })
});

/**
 * 创建矢量图层
 */
hvectorSource = new ol.source.Vector();
hvector_layer = new ol.layer.Vector({
    name: '多边形图层',
    source: hvectorSource, // 加载数据源
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255,0)'
        }),
        stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({
                color: '#ffcc33'
            })
        })
    })
});

/**
 * 绘制查询结果到矢量图层
 */
function hdrawWktFeatures(data, zoomlevel) {
    var wktformate = new ol.format.WKT();
    $.each(data, function (i, n) {
        var id = n.id;
        var wkt = n.geom;
        console.log(wkt);
        var feature = wktformate.readFeature(wkt, {
            dataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
        });

        hdrawFeature(feature);
    });

    var extent = hvectorSource.getExtent();
    hmap.getView().setZoom(zoomlevel);
    hmap.getView().setCenter(ol.extent.getCenter(extent));
}
hmap.addLayer(hvector_layer);
hvector_layer.setZIndex(3);

/**
 * 添加到图层
 */
function hdrawFeature(feature) {
    if (hvectorSource) {
        hvectorSource.addFeature(feature);
    }
}

function checkyes(status, row) {
    var pdata = {
        status: status,
        fid: row.fid,
        id: row.id,
        fdes: row.fdes,
        mark: row.mark,
        taguserid: row.taguserid,
        failreason: row.failreason,
        fname: row.fname,
        ftype: row.ftype,
        geom: row.geom
    };
    pdata = JSON.stringify(pdata);
    $.ajax({
        type: "POST",
        url: "../geo/updateTagData",
        contentType: "application/x-www-form-urlencoded",
        data: {data: pdata},
        dataType: "json",
        processData: true,
        error: function (req, status, error) {

            if (status == "timeout") {
                alert("请求超时，请稍后再试！");
                return;
            } else if (status === "error") {
                alert("数据请求失败，请稍后再试!如果还未解决，请联系管理员！");
                return;
            }
            return;
        },
        success: function () {
            alert("保存成功！");
        }
    });
}
/**
 *
 * 绘制任务区到地图
 */
function drawAuditTaskGeom(data) {
    var wktformate = new ol.format.WKT();
    $.each(data, function (i, n) {
        var id = n.taskId;
        var wkt = n.geom;

        var feature = wktformate.readFeature(wkt, {
            dataProjection: 'EPSG:4326',
            featureProjection: 'EPSG:3857'
        });
        feature.setId(id);
        if (aduitask_source) {
            aduitask_source.addFeature(feature);
        }
    });

    var extent = aduitask_source.getExtent();
    hmap.getView().setCenter(ol.extent.getCenter(extent));
    hmap.addLayer(aduitask_layer);
}
/**
 * 绘制单个要素到展示图层
 */
function ShowFeature(wkt) {

    showSource.clear();

    /**默认style**/
    var show_layer = new ol.layer.Vector({
        name: '展示图层',
        source: showSource// 加载数据源
    });

    var pointstyle = new ol.style.Style({
        image: new ol.style.Circle({
            fill: new ol.style.Fill({
                color: 'rgba(255,0,0,1)'
            }),
            radius: 5,
            stroke: new ol.style.Stroke({
                color: 'rgba(255,0,0,1)',
                width: 2
            })
        })
    });

    var polygonstyle = new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255,0,0,0.1)',
            width: 2
        }),
        stroke: new ol.style.Stroke({
            color: 'rgba(255,0,0,1)',
            width: 2
        })
    });

    var k = wkt.indexOf("POLYGON");
    if (k == 0) {
        show_layer.setStyle(polygonstyle);
    }

    /**默认style**/

    var wktformate = new ol.format.WKT();
    var feature = wktformate.readFeature(wkt, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
    });
    showSource.addFeature(feature);

    var extent = showSource.getExtent();
    hmap.getView().setZoom(17);
    hmap.getView().setCenter(ol.extent.getCenter(extent));

    show_layer.setZIndex(4);
    show_layer.setMap(hmap);
}

/**
 * 审核任务列表加载
 */
function queryTaskList() {
    $.ajax({
        type: 'GET',
        url: "../geo/getTaskByAuditerName",
        dataType: "json",
        processData: true,
        error: function (req, status, error) {
            if (status == "timeout") {
                alert("请求超时，请稍后再试!！");
                return;
            } else if (status === "error") {
                alert("数据请求失败，请稍后再试!如果还未解决，请联系管理员！");
                return;
            }
            return;
        },
        success: function (obj) {
            var rows = [];
            //添加任务区绘制
            $.each(obj, function (i, n) {
                var tskid = n.taskId;
                var dpsbtn = "<button title='加载' style='background:url(/geo/resources/images/edit_add.png);background-repeat:no-repeat;height:20px;width:20px'></button>";
                var psbtn = "<button title='通过' style='background:url(/geo/resources/images/pass.png);background-repeat:no-repeat;height:20px;width:20px'></button>";
                var npbtn = "<button title='不通过' style='background:url(/geo/resources/images/no.png);background-repeat:no-repeat;height:20px;width:20px'></button>";
                var fcheck = "<select id='" + "taskFailreas" + tskid + "'><option value='请选择'>请选择</option><option value='要素漏提'>要素漏提</option><option value='图幅混乱'>图幅混乱</option><option value='任务未完成'>任务未完成</option><option value='要素审核不通过'>要素审核不通过</option></select>"
                rows.push({
                    ctaskid: tskid,
                    cdldtask: dpsbtn,
                    cpstsk: psbtn,
                    cnpastsk: npbtn,
                    creason: fcheck
                });
            });
            $("#checkerTaskList").datagrid({data: rows, checkOnSelect: false});
            $("#checkerTaskList").datagrid({
                onClickCell: function (index, field, value) {
                    //加载 单个 审核任务
                    if (field === "cdldtask") {
                        var getrow = $(this).datagrid("getData").rows[index];
                        var tskid = getrow.ctaskid;
                        hvectorSource.clear();
                        queryFeatureByAduitor(tskid);
                        queryTaskGeom(tskid);
                        return;
                    }
                    //整个任务通过
                    if (field === "cpstsk") {
                        var getrow = $(this).datagrid("getData").rows[index];
                        var tskid = getrow.ctaskid;
                        $(this).datagrid("deleteRow", index);
                        var status = '3';
                        var reason = "通过";
                        passAuditTask(tskid, status, reason);
                        return;
                    }
                    //整个任务   不通过
                    if (field === "creason") {
                        var getrow = $(this).datagrid("getData").rows[index];
                        var tskid = getrow.ctaskid;
                        var status = '4';
                        var taskresid = "#taskFailreas" + tskid + "";
                        var reason = $(taskresid).val();
                        console.log(reason);
                        // var reason = $("#taskFailreas").val();
                        passAuditTask(tskid, status, reason);
                        return;
                    }
                }
            });
        }
    });
}
/**
 * 要素审核逻辑
 * @param tskid
 */
function queryFeatureByAduitor(tskid) {
    var param = {
        taskId: tskid + ""
    };
    param = JSON.stringify(param);
    $.ajax({
        type: 'POST',
        url: "../geo/getFeatureByAuditTaskId",
        data: {data: param},
        dataType: "json",
        processData: true,
        error: function (req, status, error) {
            if (status == "timeout") {
                alert("请求超时，请稍后再试!！");
                return;
            } else if (status === "error") {
                alert("数据请求失败，请稍后再试!如果还未解决，请联系管理员！");
                return;
            }
            return;
        },
        success: function (obj) {
            //要素绘制
            hdrawWktFeatures(obj, 16);
            var rows = [];
            $.each(obj, function (i, n) {
                var featureid = n.id;
                var fname = n.fname;
                var ftype = n.ftype;
                var geom = n.geom;
                var psbtn = "<button title='通过' style='background:url(/geo/resources/images/pass.png);background-repeat:no-repeat;height:20px;width:20px'></button>";
                var npbtn = "<button title='不通过' style='background:url(/geo/resources/images/no.png);background-repeat:no-repeat;height:20px;width:20px'></button>";
                var fcheck = "<select id='featureReason" + featureid + "' class='easyui-combobox'><option value='请选择'>请选择</option><option value='类别错误'>类别错误</option><option value='nameerror'>名称错误</option><option value='shortv'>缺少拐点</option><option value='topoerror'>拓扑错误</option></select>"
                rows.push({
                    featureid: featureid,
                    fname: fname,
                    geom: geom,
                    ftype: ftype,
                    febtn: psbtn,
                    fdbtn: npbtn,
                    fstatus: fcheck
                });
            });

            $("#auditfeature").datagrid({data: rows, checkOnSelect: false});

            $("#auditfeature").datagrid({
                onDblClickRow: function (index, row) {
                    var getrow = $(this).datagrid("getData").rows[index];
                    var wkt = getrow.geom;
                    //显示
                    ShowFeature(wkt);
                },
                onClickCell: function (index, field, value) {
                    if (field === "febtn") {
                        var getrow = $(this).datagrid("getData").rows[index];
                        var fid = getrow.featureid;
                        // $(this).datagrid("deleteRow", index);
                        //通过逻辑
                        var fstasut = 5 + "";
                        var reason = "通过";
                        updateFeatureAudit(fid, fstasut, reason);
                        return;
                    }
                    if (field === "npbtn") {
                        var getrow = $(this).datagrid("getData").rows[index];
                        var col = getrow.dldfid;
                        //$(this).datagrid("deleteRow", index);
                        //不通过逻辑
                        return;
                    }
                    if (field === "fstatus") {
                        var getrow = $(this).datagrid("getData").rows[index];
                        var fid = getrow.featureid;
                        // $(this).datagrid("deleteRow", index);
                        //不通过，提交不通过原因
                        var fstasut = 4 + "";
                        var taskresid = "#featureReason" + fid + "";
                        var reason = $(taskresid).val();
                        updateFeatureAudit(fid, fstasut, reason);
                        return;
                    }
                }
            });
        }
    });
}

/**
 *更新审核任务状态
 * @param tskid
 * @param status
 */
function passAuditTask(tskid, status, reason) {
    var param = {
        taskId: tskid + "",
        status: status,
        reason: reason
    };
    param = JSON.stringify(param);
    $.ajax({
        type: 'POST',
        url: "../geo/setTaskStatus",
        data: {data: param},
        dataType: "json",
        processData: true,
        error: function (req, status, error) {
            if (status == "timeout") {
                alert("请求超时，请稍后再试!！");
                return;
            } else if (status === "error") {
                alert("数据请求失败，请稍后再试!如果还未解决，请联系管理员！");
                return;
            }
            return;
        },
        success: function (obj) {
        }
    });
}

/**
 * 单个要素素审核状态
 */
function updateFeatureAudit(fid, fs, fres) {
    var param = {
        id: fid + "",
        auditStatus: fs,
        reason: fres
    };
    param = JSON.stringify(param);
    $.ajax({
        type: 'POST',
        url: "../geo/updateStatus",
        data: {data: param},
        dataType: "json",
        processData: true,
        error: function (req, status, error) {
            if (status == "timeout") {
                alert("请求超时，请稍后再试!！");
                return;
            } else if (status === "error") {
                alert("数据请求失败，请稍后再试!如果还未解决，请联系管理员！");
                return;
            }
            return;
        },
        success: function (obj) {
        }
    });
}
/**
 * 查询审核任务空间范围
 * @param tskid
 */
function queryTaskGeom(tskid) {
    var data = {
        taskid: tskid + ""
       };
    data = JSON.stringify(data);
    $.ajax({
        type: 'POST',
        url: "../geo/getTaskGeomByID",
        data: {data: data},
        dataType: "json",
        processData: true,
        error: function (req, status, error) {
            if (status == "timeout") {
                alert("请求超时，请稍后再试!！");
                return;
            } else if (status === "error") {
                alert("数据请求失败，请稍后再试!如果还未解决，请联系管理员！");
                return;
            }
            return;
        },
        success: function (obj) {
            aduitask_source.clear();
            drawAuditTaskGeom(obj);
        }
    });

}